package com.rizzo.android.content;

import android.accounts.Account;
import android.content.*;
import android.os.Bundle;
import android.util.Log;
import com.rizzo.analytics.domain.KeyType;
import com.rizzo.analytics.domain.application.Applications;
import com.rizzo.analytics.domain.info.Info;
import com.rizzo.android.content.http.StateHolder;
import com.rizzo.android.content.processor.QuotaProcessor;

import java.io.IOException;

public class RizzoSyncAdapter extends AbstractThreadedSyncAdapter {

    public RizzoSyncAdapter(Context context, boolean autoInitialize) {
        super(context, autoInitialize);
    }

    public RizzoSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
        super(context, autoInitialize, allowParallelSyncs);
    }

    @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {

        // 0. get the JSON info data from the server (StateHolder)
        // 1. run through the info data from server and update items that need to be synced to the content-provider
        // 			- update existing (error-totalusers, error-data) and insert new error-data
        // 			- update existing quota and insert new quotas
        // 			- update existing trend-data (we know from what time we have to retrieve) and insert new trends
        // do all the processing in a separate processor...
        // notification of the different users of cursors will be changed when used with the LoaderManager!!!

        StateHolder stateHolder = new StateHolder("rizzo-analytics-services.cloudfoundry.com", "jalie", "jalie", "application/json");
        try {
            Applications applications = stateHolder.getApplications();
            for (String application : applications.getApplications()) {
                // sync the quotas
                Info info = stateHolder.getInfo(application, StateHolder.WILDCARD, KeyType.ALL);
                final QuotaProcessor quotaProcessor = new QuotaProcessor(stateHolder, application, provider, syncResult);
//                final ContentProviderResult[] quotaContentProviderResults = quotaProcessor.process(info.getQuotas());
                // TODO make sure the sync is performed with a back-off if bad results were encountered
            }
        } catch (IOException e) {
            Log.e(this.getClass().getCanonicalName(), "Error while syncing the db with the cloud!", e);
            syncResult.stats.numIoExceptions++;
        }
    }


}
